<?php
namespace app\api\controller;

use app\api\model\Giftpack;
use app\api\model\BonusUsers;
use app\api\model\GiftpackOrder;
require_once VENDOR_PATH.'Wxpay/lib/WxPay.Api.php';
require_once VENDOR_PATH.'Wxpay/lib/WxPay.Notify.php';
class Giftpacknotify extends \WxPayNotify{
    //查询订单
    public function Queryorder($transaction_id,$out_trade_no)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);

        $notifyResult = false;
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            $notifyResult = $this->orderGoods($out_trade_no);
        }

        ob_clean();
        if($notifyResult){
            return true;
        }
        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {
        $notfiyOutput = array();
        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";
            return false;
        }

        //查询订单，判断订单真实性
        if(!$this->Queryorder($data["transaction_id"],$data['out_trade_no'])){
            $msg = "订单查询失败";
            return false;
        }
        return true;
    }

    //礼包回调
    public function orderGoods($order_sn='202407121739303466')
    {
        //订单查询
        $order = GiftpackOrder::where(['order_sn'=>$order_sn])->find();
        if($order['order_status'] == 1){
            //已付款
            return true;
        }else{
            //发放奖励
            $addData = [
                'users_id'      =>      $order['users_id'],
                'bonus_id'      =>      $order['bonus_id'],
                'num'           =>      $order['num'],
                'endtime'       =>      $order['tian']*86400+time(),
                'addtime'       =>      time(),
                'type'          =>      2,
                'order_id'      =>      $order['id']
            ];
            BonusUsers::insert($addData);
            //修改订单状态为已支付
            GiftpackOrder::where(['order_sn'=>$order_sn])->update(['order_status'=>'1','paytime'=>time()]);
        }
        return true;
    }

}